package com.vhly.bpplat;

import com.vhly.bpplat.twitter.HTTPClient;
import com.vhly.bpplat.twitter.model.Status;
import com.vhly.bpplat.twitter.model.TwitterParser;
import org.kxml2.io.KXmlParser;
import org.kxml2.kdom.Document;
import org.xmlpull.v1.XmlPullParserException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.Vector;
import java.util.logging.Logger;


/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-3-22
 * Time: 11:11:22
 */
public class TuiTeServlet extends HttpServlet {

    private static Logger log = Logger.getLogger("TuiTeServlet");

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        process(request, response);
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    private void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO implement process
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String method = request.getMethod();
        String action = request.getParameter("ac");
        if (method.equals("POST")) {
            if (action != null) {
                if (action.equals("uptw")) {
                    processUpdateTweet(request, response);
                } else if (action.equals("su")) {
                    processShortenURL(request, response);
                }
            }
        } else {
            if (action != null) {
                if (action.equals("logout")) {
                    HttpSession session = request.getSession();
                    session.removeAttribute("user");
                    session.removeAttribute("pass");
                    session.removeAttribute("login");
                    response.setStatus(HttpServletResponse.SC_OK);
                    response.setContentType("application/x-blueprint+xml");
                    StringBuffer sb = new StringBuffer();
                    sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page>");
                    sb.append("<content><module><header layout=\"simple\"><layout-items><block class=\"title\">Logout</block></layout-items></header>");
                    sb.append("\n<block>Logout OK Back to</block>");
                    sb.append("</module></content></page>");
                    String xml1 = sb.toString();

                    writeResponseContent(response, xml1);
                } else if (action.equals("ftl")) {
                    processFriendTimeLine(request, response);
                }
            }
        }
    }

    private void processFriendTimeLine(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO process FriendTimeLine
        HttpSession session = request.getSession();
        Object login = session.getAttribute("login");
        String user = (String) session.getAttribute("user");
        String pass = (String) session.getAttribute("pass");
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/x-blueprint+xml");
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page>");
        sb.append("<content><module><header layout=\"simple\"><layout-items><block class=\"title\">Friends Tweets</block></layout-items></header>");
        if (login != null) {
            String ftl = "http://twitter.com/statuses/friends_timeline.xml";
            String acc = user + ":" + pass;
            String xml = HTTPClient.request(ftl, acc, null, false);
            if (xml != null) {
                Document dom = new Document();
                KXmlParser parser = new KXmlParser();
                byte[] buf = xml.getBytes("UTF-8");
                ByteArrayInputStream bin = null;
                Vector<Status> sts = null;
                try {
                    bin = new ByteArrayInputStream(buf);
                    parser.setInput(bin, null);
                    dom.parse(parser);
                    sts = TwitterParser.parseStatuses(dom.getRootElement());
                    for (Status st : sts) {
                        sb.append("<placard layout=\"simple\" class=\"link\"><layout-items>");
                        // TODO status output
                        sb.append("<block class=\"title\">").append(st.user.screen_name).append("</block>");
                        String stext = st.text;
                        sb.append("<block class=\"description\">").append(stext).append("</block>");
                        sb.append("<block class=\"subtext\">").append(st.create_at).append("</block>");
                        sb.append("</layout-items>");
                        sb.append("<load event=\"activate\" resource=\"info.jsp?u=").append(URLEncoder.encode(st.user.screen_name, "UTF-8")).append("&amp;t=").append(URLEncoder.encode(stext, "UTF-8")).append("\" />");
                        sb.append("</placard>");
                    }
                } catch (XmlPullParserException xe) {

                } finally {
                    if (sts != null) {
                        sts.clear();
                    }
                    buf = null;
                    xml = null;
                    parser = null;
                    try {
                        bin.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    bin = null;
                }
            } else {
                sb.append("<block>Request Happen Error</block>");
            }
        } else {
            sb.append("<block>You must login to List your friends's tweets</block>");
        }
        sb.append("</module></content></page>");
        String xml1 = sb.toString();
        writeResponseContent(response, xml1);
    }

    private void processShortenURL(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String url = request.getParameter("surl");
        String serv = request.getParameter("sv");
        if (serv == null) {
            serv = request.getParameter("sserv");
        }
        if (serv == null) {
            serv = "sto";
        }
        String target = "";
        String eu = URLEncoder.encode(url, "UTF-8");
        if (serv.equals("sto")) {
            target = "http://short.to/s.txt?url=" + eu;
        } else if (serv.equals("isgd")) {
            target = "http://is.gd/api.php?longurl=" + eu;
        } else if (serv.equals("307")) {
            target = " http://a.307.to/api2/post?format=text&u=" + eu;
        } else if (serv.equals("cligs")) {
            target = "http://cli.gs/api/v1/cligs/create?key=8f665e86b9e563cf4a9df9707753317c&appid=TuiTe&url=" + eu;
        } else if (serv.equals("toly")) {
            target = "http://to.ly/api.php?longurl=" + eu;
        } else if (serv.equals("xr")) {
            target = "http://api.xr.com/api?link=" + eu;
            // this service will add a Frame
        } else {
            target = "http://short.to/s.txt?url=" + eu;
        }
        String surl = HTTPClient.request(target, null, null, false);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/x-blueprint+xml");
        StringBuffer sb = new StringBuffer();
        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page>");
        sb.append("<models><model><instance><data xmlns=\"\"><url>");
        sb.append(surl).append("</url></data></instance></model></models>");
        sb.append("<content><module><header layout=\"simple\"><layout-items><block class=\"title\">Shorten URL</block></layout-items></header>");
        sb.append("<input ref=\"url\"><label>Shorten URL</label></input>");
        sb.append("</module></content></page>");
        String xml1 = sb.toString();
        writeResponseContent(response, xml1);
    }

    private void writeResponseContent(HttpServletResponse response, String xml1) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        out.print(xml1);
        out.close();
    }

    private void processUpdateTweet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String status = request.getParameter("status");
        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("user");
        String pass = (String) session.getAttribute("pass");
        Object login = session.getAttribute("login");
        if (login != null) {
            status = "status=" + URLEncoder.encode(status, "UTF-8");
            String rid = request.getParameter("rid");
            if (rid != null && rid.length() > 0) {
                status = status + "&in_reply_to_status_id=" + URLEncoder.encode(rid, "UTF-8");
            }
            String acc = user + ":" + pass;
            String xml = HTTPClient.request("http://twitter.com/statuses/update.xml", acc, status.getBytes("UTF-8"), false);
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/x-blueprint+xml");
            StringBuffer sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page><content><module><header layout=\"simple\"><layout-items><block class=\"title\">TuiTe for Mobile</block></layout-items></header>");
            if (xml != null) {
                sb.append("<block>Update Success</block>");
            } else {
                sb.append("<block>Update Faile</block>");
            }
            sb.append("</module></content></page>");
            String xml1 = sb.toString();
            writeResponseContent(response, xml1);
        } else {
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentType("application/x-blueprint+xml");
            StringBuffer sb = new StringBuffer();
            sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page><content><module><header layout=\"simple\"><layout-items><block class=\"title\">TuiTe for Mobile</block></layout-items></header>");
            sb.append("<block>Need Login</block>");
            sb.append("</module></content></page>");
            String xml1 = sb.toString();
            writeResponseContent(response, xml1);
        }
    }

//    private void processLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        String name = request.getParameter("name");
//        String pass = request.getParameter("pass");
//        HttpSession session = request.getSession();
//        session.setAttribute("login", "true");
//        session.setAttribute("user", name);
//        session.setAttribute("pass", pass);
//        session.setMaxInactiveInterval(360000);
//        response.setStatus(HttpServletResponse.SC_OK);
//        response.setContentType("application/x-blueprint+xml");
//        StringBuffer sb = new StringBuffer();
//        sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<page><content><module><header layout=\"simple\"><layout-items><block class=\"title\">TuiTe for Mobile</block></layout-items></header>");
//        sb.append("<block>Welcome ").append(name).append("</block>");
//        sb.append("<trigger><label>Update Status</label><load event=\"activate\" resource=\"hellov.jsp\" /></trigger>");
//        sb.append("</module></content></page>");
//        String xml = sb.toString();
//        writeResponseContent(response, xml);
//    }
}
